package main

import (
	"context"
	"demo1/proto"
	"errors"
	"fmt"
	"github.com/afex/hystrix-go/hystrix"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/client"
	"github.com/micro/go-plugins/registry/etcdv3/v2"
	"time"
)
type MyclientWrapper struct {
	client.Client
}
func (c *MyclientWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
	return hystrix.Do(req.Service()+"."+req.Endpoint(), func() error {
		return c.Client.Call(ctx, req, rsp, opts...)
	}, func(err error)error{
		fmt.Println("客户端熔断，再此进行==》服务降级，可在此使用备用服务")
		return errors.New("客户端熔断了")
	})
}
// NewClientWrapper returns a hystrix client Wrapper.
func NewClientWrapper() client.Wrapper {
	return func(c client.Client) client.Client {
		return &MyclientWrapper{c}
	}
}
/**
rpc服务调用client端
 */
func main(){
	//hystrix.DefaultTimeout = 1000 //命令执行超时时间
	//hystrix.DefaultMaxConcurrent = 1000 //熔断最大并发数
	myclient := micro.NewService(
		micro.Name("student-client"),
		micro.Version("v1.0.0"),
		micro.Registry(etcdv3.NewRegistry()),
		micro.WrapClient(NewClientWrapper()),//熔断处理
		)
	myclient.Init()
	//调用rpc方法
	s := proto.NewStudentServerService("student-service",myclient.Client())
	//模拟多客户端并发请求
	t := time.NewTicker(200*time.Millisecond)
	for t := range t.C {
		student,err := s.GetStudent(context.TODO(),&proto.ReqStudent{Name:"ztind"})
		if err!=nil{
			fmt.Println("请求错误",err.Error())
		}else {
			fmt.Println(*student,t)
		}
	}
}
